//////////////////////////////////////////////////////////////////////////
// $Id: DynamicTexture.cpp,v 1.1 2009/04/03 12:46:11 sunjun Exp $
//////////////////////////////////////////////////////////////////////////

#include "Local.h"

//////////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////////

NAMESPACE_BEGIN

//////////////////////////////////////////////////////////////////////////

	DynamicTexture::DynamicTexture( const Context* rc ) : Texture(rc) 
	{
		
	}

	DynamicTexture::~DynamicTexture() 
	{
		if((IDirect3DTexture9*)mHandle){((IDirect3DTexture9*)mHandle)->Release(); mHandle = NULL;}
	}

	//////////////////////////////////////////////////////////////////////////

	/*
	====================
	load
	====================
	*/
	INLINE VOID DynamicTexture::load( const VOID* data, U32 size )
	{
		CHECK(data);
		CHECK(mHandle==NULL);

		// check the data header
		U8 * data_ptr = (U8*)data;

		// get the type
		U32 type = *(U32*)data_ptr;
		data_ptr += sizeof(U32);
		CHECK(type == TT_TEXTURE);

		// get the format
		U32 format = *(U32*)data_ptr;
		data_ptr += sizeof(U32);

		// get the width
		U32 width = *(U32*)data_ptr;
		data_ptr += sizeof(U32);		
		
		// get the height
		U32 height = *(U32*)data_ptr;
		data_ptr += sizeof(U32);

		// create the render texture
		IDirect3DTexture9 *d3d9Texture = NULL;
		HRESULT hr = ((IDirect3DDevice9*)mRCPtr->handle())->CreateTexture(width, height, 0, D3DUSAGE_DYNAMIC, (D3DFORMAT)format, D3DPOOL_DEFAULT, &d3d9Texture, NULL);
		if(FAILED(hr)) MAssert(VA("DynamicTexture::load : create the render texture is failed(%s)!", DXGetErrorDescription(hr)));
		mHandle = d3d9Texture;		
	}

	/*
	====================
	lock
	====================
	*/
	INLINE VOID DynamicTexture::lock( VOID** bits, I32* pitch, const RECT* rect )
	{
		D3DLOCKED_RECT d3dLockedRect;
		HRESULT hr = ((IDirect3DTexture9*)mHandle)->LockRect(0, &d3dLockedRect, rect, 0);
		if(FAILED(hr)) MAssert(VA("DynamicTexture::lock : lock the dynamic texture is failed(%s)!", DXGetErrorDescription(hr)));
		(*bits) = d3dLockedRect.pBits;
		(*pitch) = d3dLockedRect.Pitch;
	}

	/*
	====================
	unlock
	====================
	*/
	INLINE VOID DynamicTexture::unlock()
	{
		HRESULT hr = ((IDirect3DTexture9*)mHandle)->UnlockRect(0);
		if(FAILED(hr)) MAssert(VA("DynamicTexture::UnlockRect : unlock the dynamic texture is failed(%s)!", DXGetErrorDescription(hr)));
	}

//////////////////////////////////////////////////////////////////////////

NAMESPACE_END

//////////////////////////////////////////////////////////////////////////
